/**
 * 
 */
package com.zznode.client.wlanpolling.service.xml;

import java.io.InputStream;

import javax.xml.namespace.QName;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;

import org.w3c.dom.Document;

/**
 * @author Bean
 *
 */
public class XmlXPathAdaptor {
	private Document document;
	
	//public 
	public XmlXPathAdaptor(InputStream is) throws XmlParserException {
		DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
		builderFactory.setNamespaceAware(true);
		try {
			DocumentBuilder builder = builderFactory.newDocumentBuilder();
			document = builder.parse(is);
		} catch (Exception exp) {
			throw new XmlParserException(exp.getMessage());
		}
	}
	
	/**
	 * 返回值的类型由 type决定
	 * @param expression
	 * @param type eg. XPathConstants.NODE/NODESET
	 * @return
	 * @throws XmlParserException
	 */
	public Object evaluate(String expression, QName type) throws XmlParserException {
		XPath xpath = XPathFactory.newInstance().newXPath();
		Object node = null;
		try {
			node = xpath.evaluate(expression, document, type);
		} catch (XPathExpressionException e) {
			throw new XmlParserException(e.getMessage());
		}
		
		return node;
	}
}
